package com.freewater.javabase.demo.network.networkinterfaces;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

// NetworkInterface标识一个本地IP地址。可以是一个物理接口，如额外的以太网卡，也可以是一个虚拟接口，与机器的其他IP地址绑定到同一个物理硬件；
public class NetworkInterfaceDemo {
    public static void main(String[] args) throws SocketException, UnknownHostException {
        // 获取名为"en4"的网络接口
        NetworkInterface networkInterface = NetworkInterface.getByName("en4");
        System.out.println(networkInterface);
        // 查询与指定ip绑定的网络接口
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        networkInterface = NetworkInterface.getByInetAddress(inetAddress);
        System.out.println(networkInterface);
        // 枚举本地所有的网络接口
        final Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            System.out.println("---------------------");
            final NetworkInterface ni = enumeration.nextElement();
            System.out.println(ni);
            final Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                System.out.println(inetAddresses.nextElement());
            }
        }
    }
}
